<template>
  <div>
    <!-- 搜索 -->
    <div class="search">
      <el-input placeholder="请输入商品名称" clearable v-model="queryInfo.goodsName"></el-input>
      <el-select placeholder="选择商品类型" clearable v-model="queryInfo.cateId" filterable default-first-option>
        <el-option v-for="cate of cateData" :label="cate.cateName" :value="cate.id" :key="cate.id"></el-option>
      </el-select>
      <el-input placeholder="请输入商品价格" clearable v-model="queryInfo.price"></el-input>
      <el-select placeholder="选择商品状态" clearable v-model="queryInfo.state">
        <el-option label="启用" value="0"></el-option>
        <el-option label="禁用" value="1"></el-option>
      </el-select>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55"></el-table-column>
      <el-table-column prop="goodsName" label="商品名称" show-overflow-tooltip></el-table-column>
      <el-table-column label="图片" width="122">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="cateName" label="商品类型" width="100"></el-table-column>
      <el-table-column prop="price" label="商品价格" width="80"></el-table-column>
      <el-table-column prop="storage" label="库存量" width="80"></el-table-column>
      <el-table-column prop="hits" label="浏览量" width="80"></el-table-column>
      <el-table-column prop="sellNum" label="销量" width="80"></el-table-column>
      <el-table-column label="商品状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" :active-value="0" :inactive-value="1" @change="handleStateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="introduce" label="商品详情" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="添加时间" width="160"></el-table-column>
      <el-table-column label="操作"  width="180" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEdit(scope.row.id)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-button type="danger"  @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false" @close="handleDialogClose">
      <el-form label-width="140px" size="small" style="width: 85%;" :model="form" :rules="rules" ref="dialogForm">
        <el-form-item prop="goodsName" label="商品名称">
          <el-input v-model="form.goodsName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="img" label="商品图片">
          <el-upload action="/api/file/upload" ref="img" :on-success="handleImgUploadSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="cateId" label="商品类型">
          <el-select placeholder="选择商品类型" clearable v-model="form.cateId" filterable default-first-option>
            <el-option v-for="cate of cateData" :label="cate.cateName" :value="cate.id" :key="cate.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="商品价格">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="storage" label="库存量">
          <el-input v-model="form.storage" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="introduce" label="商品详情">
          <el-input type="textarea" rows="3" v-model="form.introduce" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Goods",
  data() {
    return {
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 查询条件
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      // 表单数据
      form: {
        hits: 0,
        sellNum: 0,
      },
      // 对话框标题
      dialogTitle: "",
      // 对话框是否显示
      dialogFormVisible: false,
      // 批量选择
      multipleSelection: [],
      // 用户信息
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      // 校验规则
      rules: {
        goodsName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        cateId: [
          {required: true, message: '请输入商品类型', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入商品价格', trigger: 'blur'}
        ],
        storage: [
          {required: true, message: '请输入库存量', trigger: 'blur'}
        ],
        introduce: [
          {required: true, message: '请输入商品详情', trigger: 'blur'}
        ],
      },
      // 商品类型数据
      cateData: [],
    }
  },
  created() {
    this.load()
  },
  methods: {
    // 加载数据
    load() {
      // 加载商品
      this.request.get("/goods/page", {
        params: this.queryInfo
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
      // 加载商品类型
      this.request.get("/cate").then(res => {
        this.cateData = res.data
      })
    },
    // 添加
    handleAdd() {
      this.dialogTitle = "添加商品"
      this.dialogFormVisible = true
    },
    // 修改
    async handleEdit(id) {
      const res = await this.request.get("/goods/" + id)
      this.form = res.data
      this.dialogTitle = "修改商品"
      this.dialogFormVisible = true
    },
    // 保存
    save() {
      this.$refs.dialogForm.validate(async valid => {
        if (!valid) {
          return
        }
        const res = await this.request.post("/goods", this.form)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        this.$message.success("保存成功")
        this.dialogFormVisible = false
        this.load()
      })
    },
    // 删除
    del(id) {
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          const res = await this.request.delete("/goods/" + id)
          if (res.code !== 200) {
            return this.$message.error("删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === 1 && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除
    delBatch() {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择需要删除的数据")
        return
      }
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          let ids = this.multipleSelection.map(item => item.id)
          const res = await this.request.delete("/goods/del/batch", {data: ids})
          if (res.code !== 200) {
            return this.$message.error("批量删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === ids.length && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 重置
    reset() {
      this.queryInfo = {
        pageNum: 1,
        pageSize: 5
      }
      this.load()
    },
    // 监听页大小改变
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.load()
    },
    // 监听页码改变
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum
      this.load()
    },
    // 文件上传成功的回调
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    // 图片上传成功的回调
    handleImgUploadSuccess(res) {
      this.form.img = res
    },
    // 下载
    download(url) {
      window.open(url)
    },
    // 导出
    exp() {
      window.open("http://localhost:7777/goods/export")
    },
    // 导入
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()
    },
    // 对话框关闭
    handleDialogClose() {
      this.dialogFormVisible = false
      this.form = {}
      this.$refs.dialogForm.resetFields() // 重置表单
      if (this.$refs.img) {
        this.$refs.img.clearFiles();
      }
      if (this.$refs.file) {
        this.$refs.file.clearFiles();
      }
    },
    
    // 修改商品状态（启用/禁用）
    handleStateChange(row) {
      this.request.post('/goods', row).then(() => {
        this.$message.success('状态更新成功')
      }).catch(() => {
        row.state = !row.state
        this.$message.error('状态更新失败')
      })
    },
  }
}
</script>

<style scoped style="less">
.search{
  margin: 10px 0;

  .el-input {
    width: 150px;
    margin-right: 10px;
  }
  .el-select {
    width: 140px;
    margin-right: 10px;
  }
}

.headerBg {
  background: #eee!important;
}
</style>